/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.language;

import com.flexengine.logger.Logger;
import com.flexengine.utils.ResourceManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class LanguageManager {
    
    private static String defaultLanguage;
    private final static HashMap<String,Language> languages;
    static {
        languages       = new HashMap<>();
        defaultLanguage = "Default";
    }
    
    public static void setDefaultLanguage(String langName) {
        if( languages.containsKey(langName) ) {
            defaultLanguage = langName;
            Logger.logMessage("LanguageManager v1.0b - setDefaultLanguage to ["+langName+"]...");
        } else {
            Logger.logMessage("LanguageManager v1.0b - Language ["+langName+"] is not available...");
        }
    }
    
    public static Language getLanguage() {
        Logger.logMessage("getLanguage(): init...");
        if( languages.isEmpty() ) {
            loadLanguages();
        }
        return languages.get(defaultLanguage);
    }
    
    public static boolean installLanguage(Language language) {
        return installLanguage(language.getName(), language);
    }
    public static boolean installLanguage(String name, Language language) {
        try {
            languages.put(name, language);
        } catch(Exception e) {
            Logger.logError("LanguagerManager v1.0b installLanguage() - ERROR: "+e);
        }
        return false;
    }
    
    public static Language getLanguage(String name) {
        return languages.get(name);
    }
    public static boolean containsLanguage(String name) {
        return languages.containsKey(name);
    }
    
    /**
     * Load and install all fonts that are disponible in LANGUAGE PATH...<br/>
     * Language have extension: .lang
     * @see LanguageFilter.LANGUAGE_FILTER
     */
    public static void loadLanguages() {
        languages.clear();
        try {
            File langPath = new File(ResourceManager.getLocale(ResourceManager.LANGUAGE_PATH));
            File[] langs = langPath.listFiles(new LanguageFilter());
            if( langs==null || langs.length<=0 ) {
                languages.put(defaultLanguage, new Language());
                return;
            }
            for (File lang1 : langs) {
                Scanner input = new Scanner(lang1);
                String langName = lang1.getName().replace(LanguageFilter.LANGUAGE_FILTER, "");
                String   line;
                Language lang = new Language();
                int      nLines = 0;
                while (input.hasNextLine()) {
                    // Read a line...
                    try {
                        line = input.nextLine();
                        nLines++;
                        if( nLines == 1 && line.startsWith("[") && line.endsWith("]") ) {
                            langName = line.replace("[", "").replace("]", "");
                            continue;
                        }
                        // Jump comments or empty lines...
                        if( line.startsWith("#") || line.startsWith("//") || line.startsWith("--") || line.trim().isEmpty() ) {
                            continue;
                        }
                        String dados[] = line.split(" ",2);
                        int macro = Integer.valueOf(dados[0]);
                        String value = dados[1];
                        lang.put(macro, value);
                    } catch (NumberFormatException e) {
                        Logger.logWarning("LanguageManager - loadLanguages(): "+e);
                        Logger.logWarning("\tFile: " + lang1 + " - Line: " + nLines);
                    }
                }
                lang.setName(langName);
                languages.put(langName, lang);
                Logger.logMessage("LanguagerManager - loadLanguages(): Language ["+langName+"] was loaded...");
            }
            defaultLanguage = languages.keySet().iterator().next();
            Logger.logMessage("LanguagerManager - loadLanguages(): Default language is ["+defaultLanguage+"]...");
        } catch(FileNotFoundException e) {
            Logger.logError("LanguagerManager - loadLanguages(): ERROR: "+e.getMessage());
        }
    }
    public static Language loadLanguage(String file) {
        try {
            file = file.endsWith(".lang") ? file : file+".lang";
            File fLang = new File(ResourceManager.getLocale(ResourceManager.LANGUAGE_PATH+file));
            Scanner  input   = new Scanner(fLang);
            String   langName = fLang.getName().replace(LanguageFilter.LANGUAGE_FILTER, "");
            String   line;
            Language lang = new Language();
            int      nLines = 0;
            while( input.hasNextLine() ) {
                // Read a line...
                try {
                    line = input.nextLine();
                    nLines++;
                    if( nLines == 1 && line.startsWith("[") && line.endsWith("]") ) {
                        langName = line.replace("[", "").replace("]", "");
                        lang.setName(langName);
                        continue;
                    }
                    // Jump comments...
                    if( line.startsWith("#") || line.startsWith("//") || line.startsWith("--") )
                        continue;
                    String dados[] = line.split(" ",2);
                    int macro = Integer.valueOf(dados[0]);
                    String value = dados[1];
                    lang.put(macro, value);
                    System.out.println("macro = "+macro+" | value = "+value);
                }
                catch(NumberFormatException e) {
                    Logger.logWarning("LanguageManager - loadLanguages(): "+e);
                    Logger.logWarning("\tFile: "+fLang+" - Line: "+nLines);
                }
            }
            Logger.logMessage("LanguagerManager - loadLanguages(): Language ["+langName+"] was loaded...");
            return lang;
        } catch(FileNotFoundException e) {
            Logger.logError("LanguagerManager v1.0b loadLanguage() - ERROR: "+e);
        }
        return null;
    }
    
    public static Language[] getAllAvailableLanguages() {
        Language langs[] = new Language[languages.size()];
        int i = 0;
        for( String k : languages.keySet() ) {
            langs[i] = languages.get(k);
            i++;
        }
        return langs;
    }
    
    public static List<Language> getAllvailableLanguages() {
        ArrayList<Language> langs = new ArrayList<>();
        for( String langName : languages.keySet() ) {
            langs.add(languages.get(langName));
        }
        return langs;
    }
    
}
